package org.robot.scm.platform.server.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.utils.RandomUtil;

@Slf4j
@NoArgsConstructor
public class HotKitHandler extends BaseHandler implements HttpHandler {

    public static void main(String[] args) {
        System.out.println(RandomUtil.uuidNoLine());
    }

    @Override
    public String getUri() {
        return "/hotkit";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("GET")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }
        String path = exchange.getRequestURI().getPath();
        File file = new File("assets" + path);
        if (!file.exists()) {
            sendFailureResponse(exchange, "404 NOT FOUND");
            return;
        }
        exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
        exchange.sendResponseHeaders(200, file.length());
        try (OutputStream responseBody = exchange.getResponseBody(); FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                responseBody.write(buffer, 0, read);
            }
        }
        exchange.close();
    }
}
